from PyQt4 import QtGui
import S3DPath
from S3D import QtHelper
from S3D.Tools.Sound.EventSearcher import QueryTasks
from S3D.Tools.Sound.EventSearcher.UI.AddQueryDialog import Ui_AddQueryDialog

class AddQueryDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(AddQueryDialog, self).__init__(parent)

        self.ui = Ui_AddQueryDialog()
        self.ui.setupUi(self)

        self.initUi()

    def initUi(self):
        for path, type in QueryTasks.TASKS:
            path = path.replace('\\', '/').split('/')
            self.addType(path, type)

    def addType(self, path, type, index=0, parent=None):
        if parent is None:
            parent = self.ui.queriesTree

        name = path[index]
        if index + 1 == len(path):
            item = QtHelper.addTreeItem(parent, name)
            item.name = name
            item.taskType = type
            return

        for item in QtHelper.treeItems(parent):
            if item.name == name:
                self.addType(path, type, index + 1, item)
                return

        item = QtHelper.addTreeItem(parent, name)
        item.setExpanded(True)
        item.name = name
        self.addType(path, type, index + 1, item)

    def onAccept(self):
        item = self.ui.queriesTree.currentItem()
        try:
            type = item.taskType
        except AttributeError:
            return

        self.selectedType = type
        self.accept()

if __name__ == '__main__':
    dlg = AddQueryDialog()
    dlg.exec_()